from datetime import datetime

from django.http import JsonResponse
from django.shortcuts import render

# Create your views here.
from django.views import View

from apps.goods.models import GoodsCategory, SKU, GoodsVisitCount
from utils.goods import get_breadcrumb, get_categories, get_goods_specs
from youshugou import settings

'''
需求：用户点击分类时显示页面
前端；发送axios请求，分类id在路由中，分页的页码(第几页数据)，每页多少条数据，排序也会传送过来
后端：
    接收请求
    将对象数据转换为字典数据
    返回json数据
    路由：GET /list/category_id/skus/
    1. 接收参数
    2. 获取分类id
    3. 根据分类id进行数据的查询验证
    4. 获取面包屑数据
    5. 查询分类对应的sku数据,排序后分页
    6. 返回响应
'''


class ListView(View):
    def get(self, request, category_id):
        try:
            category = GoodsCategory.objects.get(id=category_id)
        except GoodsCategory.DoesNotExist:
            return JsonResponse({'code': 400, 'errmsg': '参数失败'})
        ordering = request.GET.get('ordering')
        page_size = request.GET.get('page_size')  # 每页多少条数据
        page = request.GET.get('page')  # 第几页数据
        breadcrumb = get_breadcrumb(category)
        skus = SKU.objects.filter(category=category, is_launched=True).order_by(ordering)
        from django.core.paginator import Paginator
        # object_list 列表数据 object_page 一页多少条数据
        paginator = Paginator(skus, per_page=page_size)
        page_skus = paginator.page(page)
        # 将对象转换为列表数据
        sku_list = []
        for sku in page_skus.object_list:
            sku_list.append({
                'id': sku.id,
                'default_image_url': sku.default_image.url,
                'name': sku.name,
                'price': sku.price
            })
        # 获取总页码
        total_num = paginator.num_pages
        return JsonResponse({
            'code': 0,
            'errmsg': 'ok',
            'breadcrumb': breadcrumb,
            'list': sku_list,
            'count': total_num
        })


class HotGoodsView(View):
    """商品热销排行"""

    def get(self, request, category_id):
        """提供商品热销排行JSON数据"""
        # 根据销量倒序
        skus = SKU.objects.filter(category_id=category_id, is_launched=True).order_by('-sales')[:2]

        # 序列化
        hot_skus = []
        for sku in skus:
            hot_skus.append({
                'id': sku.id,
                'default_image_url': sku.default_image.url,
                'name': sku.name,
                'price': sku.price
            })

        return JsonResponse({'code': 0, 'errmsg': 'OK', 'hot_skus': hot_skus})


class DetailView(View):
    """商品详情页"""

    def get(self, request, sku_id):
        """提供商品详情页"""
        # 获取当前sku的信息
        try:
            sku = SKU.objects.get(id=sku_id)
        except SKU.DoesNotExist:
            return render(request, '404.html')

        # 查询商品频道分类
        categories = get_categories()
        # 查询面包屑导航
        breadcrumb = get_breadcrumb(sku.category)
        # 查询规格键
        goods_specs = get_goods_specs(sku)
        # 渲染页面
        context = {
            'categories': categories,
            'breadcrumb': breadcrumb,
            'sku': sku,
            'specs': goods_specs,
        }
        from django.template import loader
        detail_template = loader.get_template('detail.html')
        detail_html_data = detail_template.render(context)
        import os
        file_path = os.path.join(os.path.dirname(settings.BASE_DIR), 'front_end_pc/goods/%s.html' % sku_id)
        with open(file_path, 'w', encoding='utf-8') as f:
            f.write(detail_html_data)
        return render(request, 'detail.html', context)


# 统计分类商品访问量
class CategoryVisitCountView(View):
    def post(self, request, category_id):
        try:
            category = GoodsCategory.objects.get(id=category_id)
        except GoodsCategory.DoesNotExist:
            return JsonResponse({'code': 400, 'errmsg': '没有此分类'})
        try:
            gvc = GoodsVisitCount.objects.get(category=category, date=datetime.today())
        except GoodsVisitCount.DoesNotExist:
            GoodsVisitCount.objects.create(category=category, date=datetime.today(), count=1)
        else:  # 更新数据
            gvc.count += 1
            gvc.save()
        return JsonResponse({'code': 0, 'errmsg': 'ok'})